<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="yes" name="apple-touch-fullscreen">
    <meta name="full-screen" content="yes">
    <meta content="default" name="apple-mobile-web-app-status-bar-style">
    <meta name="screen-orientation" content="portrait">
    <meta name="browsermode" content="application">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="x5-orientation" content="portrait">
    <meta name="x5-fullscreen" content="true">
    <meta name="x5-page-mode" content="app">
    <base target="_blank">
    <title>聊天室</title>
    <link href="../static/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" href="../static/css/chat.css">
    <script src="../static/js/jquery-1.9.1.min.js"></script>

</head>

<body>
<img style="width:100%;height:100%" src="../static/img/bg.jpg">
<input type="hidden" id="userId" th:value="${session.loginUser.id}"/>
<div class="abs cover contaniner">
    <div class="abs cover pnl">
        <div class="top pnl-head" style="padding: 20px ; color: white;">
            <div id="userName"> 用户：张三<span style='float: right;color: green'>在线</span></div>
            <div id="chatMes" style="text-align: center;color: black;font-family: 新宋体">
            </div>
        </div>
        <!--聊天区开始-->
        <div class="abs cover pnl-body" id="pnlBody">
            <div class="abs cover pnl-left" id="initBackground" style="background-color: white; width: 100%">
                <div class="abs right pnl-right">
                    <div class="slider-container hide"></div>
                    <div class="pnl-right-content">
                        <div class="pnl-tabs">
                            <div class="tab-btn " id="hot-tab">好友列表</div>
                        </div>
                        <div class="pnl-hot" style="margin: 0px;padding: 0px">
                            <ul class="rel-list unselect" id="userlist">
                                <!--<li class="rel-item">-->
                                    <!--<div class="msg-host photo"-->
                                         <!--style="background-image: url(../static/img/avatar/Member002.png);display: inline-block"></div>-->
                                    <!--<a onclick='showChat("张三")'-->
                                       <!--style="font-family:FangSong;font-size: larger;text-decoration: none">张三</a></li>-->
                                <!--<hr>-->
                                <!--<li class="rel-item">-->
                                    <!--<div class="msg-host photo"-->
                                         <!--style="background-image: url(../static/img/avatar/Member003.png);display: inline-block"></div>-->
                                    <!--<a onclick='showChat("李四")'-->
                                       <!--style="font-family:FangSong;font-size: larger;text-decoration: none">李四</a></li>-->
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="abs cover pnl-left" id="chatArea" style="display: none">
                    <div class="abs cover pnl-msgs scroll" id="show">
                        <div class="pnl-list" id="hists"><!-- 历史消息 --></div>
                        <div class="pnl-list" id="msgs">
                            <!-- 消息这展示区域 -->
                            <div class="msg guest">
                                <div class="msg-right">
                                    <div class="msg-host headDefault"></div>
                                    <div class="msg-ball">你好</div>
                                </div>
                            </div>

                            <div class="msg robot">
                                <div class="msg-left" worker="">
                                    <div class="msg-host photo"
                                         style="background-image: url(../static/img/avatar/Member002.png)"></div>
                                    <div class="msg-ball">你好</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="abs bottom pnl-text">
                        <div class="abs cover pnl-input" style="padding: 0px;margin: 0px">
                            <textarea class="scroll" id="context_text" wrap="hard" placeholder="输入聊天内容..."></textarea>
                            <div class="abs atcom-pnl scroll hide" id="atcomPnl">
                                <ul class="atcom" id="atcom"></ul>
                            </div>
                        </div>
                        <button class="abs br btn-1 custom-btn" id="submit"><span>发送</span></button>
                    </div>
                </div>
                <!--聊天区 结束-->
            </div>
        </div>
    </div>
</div>
<script>

    var userId;
    var toName;
    var username;

    function showChat(name) {
        toName = name;
        //现在聊天对话框
        $("#chatArea").css("display", "inline");
        //清空聊天区
        $("#msgs").empty();

        //显示“正在和谁聊天”
        $("#chatMes").html("正在和" + toName + "聊天");
        // //sessionStorage
        // var chatData = sessionStorage.getItem(toName);
        // if (chatData != null) {
        //     //将聊天记录渲染到聊天区
        //     $("#msgs").html(chatData);
        // }
        $.ajax({
            url: "http://localhost:8080/message/list/" + userId + "/" + toName,
            success: function (res) {
                console.log(res.data)
                for(var i=0; i<res.data.length; i++) {
                    var str = '';
                    if (res.data[i].userId == userId) {
                        str = "<div class=\"msg guest\"><div class=\"msg-right\" worker=\"\"><div class=\"msg-host headDefault\"></div><div class=\"msg-ball\">" + res.data[i].content + "</div></div></div>";
                    } else {
                        str = "<div class=\"msg robot\"><div class=\"msg-left\" worker=\"\"><div class=\"msg-host photo\" style=\"background-image: url(../static/img/avatar/Member002.png)\"></div><div class=\"msg-ball\">" + res.data[i].content + "</div></div></div>";
                    }
                    $("#msgs").append(str);
                }
            },
            async: false
        })
    }

    $(function () {
        userId = $("#userId").val();
        console.log("userId=" + userId);
        $.ajax({
            url: "http://localhost:8080/user/getUsername/" + userId,
            success: function (res) {
                username = res;
                //显示在线信息
                $("#userName").html(" 用户：" + res + "<span style='float: right;color: green'>在线</span>");
            },
            async: false
        })
        $.ajax({
            url: "http://localhost:8080/friend/list?selfId="+userId,
            success: function (res) {
                console.log(res);
                var str = '';
                for(var i=0; i<res.length; i++) {
                    str = ("<li class=\"rel-item\"><div class=\"msg-host photo\" style=\"background-image: url(../static/img/avatar/Member002.png);display: inline-block\"></div><a onclick='showChat(\"" + res[i].friendName + "\")'style=\"font-family:FangSong;font-size: larger;text-decoration: none\">" + res[i].friendName + "</a></li><hr/>");
                    $("#userlist").append(str);
                }

            },
            async: false
        })


        //创建webSocket对象
        var ws = new WebSocket("ws://localhost:8080/chat/" + userId);
        //给ws绑定事件
        ws.onopen = function () {
            //在建立连接后需要做什么事？
            //显示在线信息
            $("#userName").html(" 用户：" + username + "<span style='float: right;color: green'>在线</span>");
        }

        //接收到服务端推送的消息后触发
        ws.onmessage = function (evt) {
            //获取服务端推送过来的消息
            var dataStr = evt.data;
            //将dataStr 转换为json对象
            var res = JSON.parse(dataStr);
            //判断是否是系统消息
            if (res.isSystem) {
                //系统消息
                var names = res.message;
                //1,好友列表展示
                //2,系统广播的展示
                var userlistStr = "";
                var broadcastListStr = "";
                for (var name of names) {
                    if (name != username) {
                        userlistStr += "<li class=\"rel-item\"><div class=\"msg-host photo\" style=\"background-image: url(../static/img/avatar/Member002.png);display: inline-block\"></div><a onclick='showChat(\"" + name + "\")'style=\"font-family:FangSong;font-size: larger;text-decoration: none\">" + name + "</a></li><hr/>";
                        broadcastListStr += "<li class=\"rel-item\" style=\"color: #9d9d9d;font-family: 宋体\">您的好友 " + name + " 已上线</li>";
                    }
                }
                //渲染好友列表和系统广播
                //$("#userlist").html(userlistStr);
                $("#broadcastList").html(broadcastListStr);

            } else {


                //不是系统消息
                //将服务端推送的消息进行展示
                var str = "<div class=\"msg robot\"><div class=\"msg-left\" worker=\"\"><div class=\"msg-host photo\" style=\"background-image: url(../static/img/avatar/Member002.png)\"></div><div class=\"msg-ball\">" + res.message + "</div></div></div>";
                if (toName == res.fromName) {
                    $("#msgs").append(str);
                }
                // var chatData = sessionStorage.getItem(res.fromName);
                // if (chatData != null) {
                //     str = chatData + str;
                // }
                // sessionStorage.setItem(res.fromName, str);
            }
        }

        ws.onclose = function () {
            //显示离线信息
            $("#userName").html(" 用户：" + username + "<span style='float: right;color: red'>离线</span>");
        }

        $("#submit").click(function () {
            //获取输入的内容
            var data = $("#context_text").val();
            //清除输入区的内容
            $("#context_text").val("");

            var json = {"toName": toName, "message": data};

            //将数据展示在聊天区
            var str = "<div class=\"msg guest\"><div class=\"msg-right\"><div class=\"msg-host headDefault\"></div>" +
                "<div class=\"msg-ball\">" + data + "</div></div></div>";
            $("#msgs").append(str);

            // var chatData = sessionStorage.getItem(toName);
            // if (chatData != null) {
            //     str = chatData + str;
            // }
            //
            // sessionStorage.setItem(toName, str)

            //发送数据给服务端
            ws.send(JSON.stringify(json));
        });
    })

</script>
</body>
</html>
